<?php

use LucaDegasperi\OAuth2Server\Authorizer;
use Rootant\Api\Exception\ValidationException;

class CommunityController extends CommonController
{
    public function __construct(Authorizer $authorizer)
    {
        parent::__construct($authorizer);
        $this->afterFilter('disconnect:secondary', ['only' => ['tag', 'getCommentsByTags']]);
    }

    public function tag()
    {
        $type = Input::get('type', 'all');

        if ($type !== 'all' && $type !== 'hot') {
            // 参数既不是 all 也不是 hot
            throw new ValidationException('参数传递错误！');
        }

        $tag = $this->dbRepository('secondary', 'tag');

        if ($type === 'hot') {
            // 热门标签
            $tag->where('is_hot', '=', 1)->orderBy('reorder', 'desc')->take(5);
        }

        return $tag->select('id', 'name')->get();
    }

    public function getCommentsByTags($tagStr)
    {
        $tag = DB::connection('secondary')->table('tag')
            ->whereIn('id', explode(',', $tagStr))
            ->implode('name', ',');

        $csi_comment = $this->getCsiComment($tag);

        foreach ($csi_comment as $comment) {
            $comment->owner = $comment->user;
            // release some var
            unset($comment->user_id, $comment->user_ip, $comment->updated_at);
        }

        $sisi_comment = $this->getSisiComment($tag);
        foreach ($sisi_comment as $comment) {
            $comment->owner = $comment->user;
            // release some var
            unset($comment->user_id, $comment->user_ip, $comment->updated_at);
        }

        $csp_comment = $this->getCommentByTag($tag);

        return array_merge($csi_comment, $sisi_comment, $csp_comment);
    }

    protected function getCommentByTag($tag)
    {
        $comments = DB::connection('major')
            ->table('journal_comment')
            ->where('tag', '=', $tag)
            ->latest('created_at')
            ->take(1)
            ->get();
        $comments = $this->processCommentResponse($comments);

        foreach ($comments as $comment) {
            $comment->flag = '3';
            $comment->article = $this->getJournalById($comment->journal_id);
            $comment->owner = $comment->user;
            // release some var
            unset($comment->user);
        }

        return $comments;
    }

}